/** EasyWeb iframe v3.1.8 date:2020-05-04 License By http://easyweb.vip */
layui.config({  // common.js是配置layui扩展模块的目录，每个页面都需要引入
    version: '318',   // 更新组件缓存，设为true不缓存，也可以设一个固定值
    base: getProjectUrl() + 'assets/module/'
}).extend({
    steps: 'steps/steps',
    notice: 'notice/notice',
    cascader: 'cascader/cascader',
    dropdown: 'dropdown/dropdown',
    fileChoose: 'fileChoose/fileChoose',
    Split: 'Split/Split',
    Cropper: 'Cropper/Cropper',
    tagsInput: 'tagsInput/tagsInput',
    citypicker: 'city-picker/city-picker',
    introJs: 'introJs/introJs',
    zTree: 'zTree/zTree'
}).use(['layer', 'admin'], function () {
    let $ = layui.jquery;
    $.fn.extend({
        /**
         * 控制选择是否显示
         * @param show
         */
        view: function (show) {
            if (show) {
                $(this).show();
            } else {
                $(this).hide();
            }
        }
    });
});
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
/** 获取当前项目的根路径，通过获取lay 全路径截取assets之前的地址 */
function getProjectUrl() {
    let layDir = layui.cache.dir;
    if (!layDir) {
        let js = document.scripts, last = js.length - 1, src;
        for (let i = last; i > 0; i--) {
            if (js[i].readyState === 'interactive') {
                src = js[i].src;
                break;
            }
        }
        let jsPath = src || js[last].src;
        layDir = jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
    }
    return layDir.substring(0, layDir.indexOf('assets'));
}

let SystemUtil = {
    BaseURL: '/',
    tinymceEle: {},
    CurrentTableInc: false,
    __: function (line, replace) {
        replace = replace || {};

        for (var key in replace) {
            if (replace.hasOwnProperty(key)) {
                var value = replace[key] + '';
                line = line.replace(':' + key, value);
                line = line.replace(':' + key.toUpperCase(), value.toUpperCase());
                line = line.replace(':' + this.ucFirst(key), this.ucFirst(value));
            }
        }
        return line;
    },
    ucFirst: function (value) {
        value = value + '';
        return value[0].toUpperCase() + value.slice(1);
    },
};

SystemUtil.chooseBaiduAddress = function (lngElem, latElem, addressElem) {
    let $lng = layui.$(lngElem), $lat = layui.$(latElem), $address = layui.$(addressElem);
    let where = {lng: $lng.val(), lat: $lat.val(), address: $address.val()};
    top.layer.open({
        type: 2,
        title: SystemUtil.lang.choose_map_location,
        btn: [SystemUtil.lang.choose, SystemUtil.lang.close],
        area: ['1024px', '600px'],
        btnAlign: 'r',
        content: [SystemUtil.BaseURL + "/index/baidu?" + layui.$.param(where), 'no'],
        yes: function (layerIndex, layero) {
            $layero = layui.$(layui.$(layero).find('iframe').get(0).contentDocument);
            $lng.val($layero.find("#hiLng").val());
            $lat.val($layero.find("#hiLat").val());
            $address.val($layero.find("#hiAddress").val());
            top.layer.close(layerIndex);
        }
    });
}

SystemUtil.choice_render = function (config) {

    layui.use(["form"], function () {
        let $ = layui.jquery;
        config = $.extend({}, {
            idField: 'id',
            showField: 'name'
        }, config);
        config.where = config.where || {};
        let $choice_container = $(config.elem);
        let $input = $choice_container.find("[type='text']");
        $choice_container.find('.layui-btn').click(function () {
            choice({});
        });
        $input.keydown(function (event) {
            if (event.keyCode === 13) {
                let url = config.url;
                let where = $.extend({}, config.where, {keyword: $input.val()});
                if (where) {
                    url = url + '?' + $.param(config.where)
                }
                SystemUtil.ajax(url, 'get').send(1).done(function (res) {
                    console.log(res);
                    if (res.count == 1) {
                        showData(res.data[0]);
                    } else if (res.count > 1) {
                        choice(where);
                    } else {
                        layer.msg(SystemUtil.lang.no_data);
                    }
                });
                event.stopPropagation();
                return false;
            }
        });
        let clearHtml = $('<i class="layui-icon layui-icon-close choice-clear"></i>');
        $choice_container.find('.choice-input').append(clearHtml);
        clearHtml.click(function () {
            $choice_container.find("[type='text']").val('');
            $choice_container.find("[type='hidden']").val(0);
        });

        function showData(item) {
            if (config.call) {
                config.call(item);
            } else {
                if (item) {
                    $choice_container.find("[type='text']").val(item[config.showField]);
                    $choice_container.find("[type='hidden']").val(item[config.idField]);
                }
            }
        }

        function choice(where) {
            let url = config.url + '_view';
            if (config.where) {
                url = url + '?' + $.param($.extend({}, config.where, where))
            }
            if (config.window) {
                win = config.window
            } else {
                win = window;
            }
            win.layer.open({
                type: 2,
                title: config.title,
                shade: 0.3,
                btn: [SystemUtil.lang.choose],
                maxmin: false, //开启最大化最小化按钮
                area: ['893px', '600px'],
                content: url,
                yes: function (index, layero) {
                    var subWindow = layero.find("iframe")[0].contentWindow;
                    if (subWindow) {
                        let status = subWindow.layui.table.checkStatus('adminTable');
                        if (status.data.length) {
                            showData(status.data[0]);
                        } else {
                            win.layer.msg('未选择任何数据');
                            return;
                        }
                    }
                    win.layer.close(index); //如果设定了yes回调，需进行手工关闭
                }
            });
        }
    });
};
/**
 *
 * @param value
 * @param defaultValue
 * @param unit
 * @param fan
 * @param fixed
 * @returns {string}
 */
SystemUtil.formatMoney = function (value, defaultValue, unit, fan, fixed) {
    value = parseFloat(value);
    defaultValue = typeof defaultValue !== 'undefined' ? defaultValue : '0.00';
    unit = typeof unit !== 'undefined' ? unit : '元';
    fan = typeof fan !== 'undefined' ? fan : false;
    fixed = typeof fixed !== 'undefined' ? fixed : defaultValue.length > 2 ? defaultValue.length - 2 : 0;

    if (typeof value == "undefined" || value == 0 || isNaN(value)) {
        return `<span class="layui-badge layui-bg-gray">${defaultValue}${unit}</span>`;
    }
    if (value > 0) {
        value = value.toFixed(fixed);
        if (fan) {
            return `<span class="layui-badge">${value}${unit}</span>`;
        } else {
            return `<span class="layui-badge layui-bg-green">${value}${unit}</span>`;
        }
    } else {
        value = value.toFixed(fixed);
        if (fan) {
            return `<span class="layui-badge layui-bg-green">${value}${unit}</span>`;
        } else {
            return `<span class="layui-badge">${value}${unit}</span>`;
        }
    }
};
/**
 *
 * @param tplUrl
 */
SystemUtil.downFile = function (tplUrl) {
    let link = document.createElement('a');
    link.setAttribute("download", "");
    link.href = tplUrl;
    link.click();
};
/**
 *
 * @param id
 */
SystemUtil.downFileById = function (id) {
    let url = SystemUtil.BaseURL + 'file/down/' + id;
    let link = document.createElement('a');
    link.setAttribute("download", "");
    link.href = url;
    link.click();
};
/**
 *
 * @param index
 */
SystemUtil.popViewSet = function (index) {
    layui.$("#layui-layer" + index + " .layui-layer-content").css({
        overflow: 'visible'
    });
};
/**
 *
 * @param time
 * @param format
 * @returns {string|*}
 */
SystemUtil.formatTime = function (time, format) {
    if (!time) return '----';
    format = typeof format !== 'undefined' ? format : 'yyyy-MM-dd';
    let date = new Date();
    date.setTime(time * 1000);
    return date.format(format);
};


/**
 * 验证正则表达式
 * @type {{egt0: RegExp, zipCode: RegExp, gt0: RegExp, money: RegExp, egt0OrOO: RegExp, mobile: RegExp, percent: RegExp, maxMoney: number, moneyNo0: RegExp}}
 */
SystemUtil.regs = {
    egt0: /^([1-9]\d*|[0])$/,
    egt0OrOO: /^([1-9]\d*|0)(\.[0]{1,2})?$/,
    gt0: /^[1-9]+\d*$/,
    percent: /(^[01]$)|(^1\.[0]{1,4}$)|(^[0]\.[0-9]{1,4}?$)/,
    zipCode: /^[0-9]{6}$/,
    mobile: /^1+[0-9]{10}$/,
    money: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0)$)|(^[0-9]\.[0-9]([0-9])?$)/,
    maxMoney: 9999999.99,
    moneyNo0: /(^[1-9]([0-9]{0,7})?(\.[0-9]{1,2})?$)|(^[0-9]\.[0-9]([0-9])?$)/
};

/**
 * lay 编辑器配置
 * @param module
 * @returns {{uploadImage: {type: string, url: string}, hideTool: [string]}}
 */
SystemUtil.layEditConfig = function (module) {
    return {
        hideTool: ['face'],
        uploadImage: {
            url: SystemUtil.BaseURL + 'file/editerImage?module=' + module,
            type: 'post'
        }
    }
};
/**
 *
 * @type {{uploadImage: SystemUtil.file.uploadImage}}
 */
SystemUtil.file = {
    uploadImage: function (btn, module, callBack) {
        let data = {};
        if (typeof (module) == 'object') {
            data = module;
        } else {
            data = {
                module: module,
                w: 64,
                h: 40
            }
        }
        layui.use('upload', function () {
            let upload = layui.upload;
            //执行实例
            console.log('up path', SystemUtil.BaseURL + "/file/uploadImage");
            let loadingIndex = false;
            let uploadInst = upload.render({
                elem: btn //绑定元素
                , data: data
                , url: SystemUtil.BaseURL + "/file/uploadImage"
                , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    loadingIndex = layer.load(); //上传loading
                }
                , done: function (res) {
                    SystemUtil.resultFilter(res, function (res) {
                        if (callBack)
                            callBack(res.data[0].id, res.data[0].url);
                    }, true);
                    layer.close(loadingIndex);
                }
                , error: function () {
                    //请求异常回调
                    layer.close(loadingIndex);
                }
            });
        });
    }
};
SystemUtil.resultFilter = function (res, callBack, notShowSuccesMsg) {
    if (res.code === 0) {
        if ((notShowSuccesMsg & 2) > 0) layer.msg(res.msg);
        if (callBack) {
            callBack(res);
        }
    } else {
        if ((notShowSuccesMsg & 1) > 0) layer.msg(res.msg);
        if (res.code == -100) {
            setTimeout(function () {
                window.location.href = res.data.referer;
            }, 3000);
        }
    }
};
SystemUtil.option = function (content, url, data) {
    layer.confirm(content, {
        title: SystemUtil.lang.tip,
        btn: [SystemUtil.lang.ok, SystemUtil.lang.cancel]
    }, function () {
        let index3 = layer.load(3);
        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json',
            success: function (res) {
                SystemUtil.resultFilter(res, function (res) {
                    parent.layer.msg(res.msg, {icon: 1, time: 1000});
                    location.reload();
                }, true);
            }
        }).always(function () {
            layer.close(index3);
        });
    });
};

SystemUtil.changeURLArg = function (url, arg, arg_val) {
    let pattern = arg + '=([^&]*)';
    let replaceText = arg + '=' + arg_val;
    if (url.match(pattern)) {
        let tmp = '/(' + arg + '=)([^&]*)/gi';
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
};

SystemUtil.approval = function (url) {
    layer.open({
        type: 1,
        title: SystemUtil.lang.auth,
        area: ['400px', '300px'],
        content: approvalTpl.innerHTML,
        btn: [SystemUtil.lang.ok, SystemUtil.lang.cancel],
        yes: function (layerIndex, layero) {
            let state = layero.find("[name='state']:checked").val();
            let reason = layero.find("[name='reason']").val();
            SystemUtil.ajax(url).setData({
                state: state,
                reason: reason
            }).send();
            layer.close(layerIndex);
        },
        success: function (layero, layerIndex) {
            $('.approval_from input').iCheck({
                radioClass: 'iradio-blue',
                increaseArea: '20%'
            });
        }
    });
};

/**
 * 系统AJAX 配置对象
 * @param url
 * @param type
 * @constructor
 */
function SystemAjaxConfig(url, type) {
    this.url = url;
    this.type = type ? type : 'post';
    this.dataType = 'json';
    this.data = {};
    this.sort = true;
    this.showLoad = true;
    this.msgMode = 1;
    this.success = function (data) {
        SystemUtil.resultFilter(data, this.deferred.resolve, this.msgMode);
        if (data.code) {
            this.deferred.reject(data);
        }
    };

    this.complete = function () {
        if (this.showLoad) {
            layer.close(this._loadIndex);
        }
    };

    this.error = function () {
        layer.msg("服务器错误", {icon: 2, time: 2000});
        this.deferred.reject("okUtils.ajax error: 服务器错误");
    };
}

SystemAjaxConfig.prototype = {

    setData(data) {
        this.data = data;
        return this;
    },
    isPost() {
        this.type = 'POST';
        return this;
    },
    noLoad() {
        this.showLoad = false;
        return this;
    },
    send: function (msgMode) {
        this.msgMode = msgMode;
        let $ = layui.$;
        this.deferred = $.Deferred();
        if (this.showLoad) {
            this._loadIndex = layer.load(3, {shade: 0.3});
        }
        $.ajax(this);
        // $promise.fail(function (e) {
        //     alert('请求失败');
        // });
        return this.deferred.promise();
    },
    set: function (k, v) {
        this[k] = v;
        return this;
    }
};

/**
 * ajax()函数二次封装
 * @param url
 * @param type
 * @returns {SystemAjaxConfig}
 */
SystemUtil.ajax = function (url, type) {
    return new SystemAjaxConfig(url, type);
};

SystemUtil.openUrl = function (title, url, area) {

    if (title == null || title == '') {
        title = false;
    }

    return layer.open({
        type: 2,
        area: area,
        fix: false, //不固定
        maxmin: false,
        shade: 0.4,
        title: title,
        content: url
    });
};

SystemUtil.openUrlContent = function (url, config) {
    SystemUtil.ajax(url, 'get').send(1).done((res) => {
        return layer.open(layui.$.extend({}, {
            type: 1,
            fix: false, //不固定
            maxmin: false,
            shade: 0.4,
            content: res.data,
            success: function (layero, index) {
                if (layui.form) {
                    layui.form.render();
                }
            }
        }, config));
    });
};
SystemUtil.openUrl2 = function (config) {
    return layer.open(layui.$.extend({}, {
        type: 2,
        shadeClose: false,
        shade: 0.2,
        maxmin: false,
        area: ['893px', '600px'],
    }, config));
};

SystemUtil.previewImg = function (img) {

    // var imgHtml = "<div style=''><img src='" + img.src.replace(/\/\d+\/\d+$/, '') + "'  style='max-width: 100%;max-height: 100%;'/></div>";

    //弹出层
    top.layer.photos({
        photos: {
            "status": 1,
            "data": [
                {
                    "alt": img.title,
                    "pid": 1,
                    "src": img.src.replace(/\/\d+\/\d+$/, ''),
                    "thumb": ""
                }
            ]
        } //格式见API文档手册页
        ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机
    });
    // top.layer.open({
    //     type: 1,
    //     shade: 0.8,
    //     offset: 'auto',
    //     area: ['80%', '80%'],
    //     shadeClose: true,
    //     scrollbar: false,
    //     title: false, //不显示标题
    //     content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
    //     cancel: function () {
    //         //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
    //     }
    // });
}
window.SystemUtil = SystemUtil;

/**
 * 列表表格配置
 * @param tableElem
 * @param url
 * @constructor
 */
function ListTable(url, tableElem) {
    this.url = url;
    this.tableId = tableElem || 'adminTable';
    this.rowBarWidth = 150;
    this.searchKey = 'searchForm';
    this.topBars = [];
    this.rowBars = [];
    this.contextMenu = [
        {
            icon: 'layui-icon layui-icon-refresh',
            name: SystemUtil.lang.refresh,
            click: function () {
                location.reload();
            }
        }
    ];
    this.rowBarFixed = 'right';
    this.rowEventKeys = {};
    this.topEventKeys = {};
    this.config = {
        elem: '#' + (tableElem || 'adminTable'),
        limit: 20,
        page: true,
        cellMinWidth: 120,
        cols: [[]],
        defaultToolbar: [],
        done: function (res, curr, count) {
            if (res.code == -100) {
                window.location.href = res.data.referer;
            }
        }
    };
    return this;
}


ListTable.prototype.setElem = function (elem) {
    this.config.elem = elem;
    return this;
};
ListTable.prototype.setData = function (data) {
    this.config.data = data;
    return this;
};

ListTable.prototype.topAddBar = function (url, config) {
    this.topBars.push({
        html: '<button class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe654;</i>' + SystemUtil.lang.create + '</button>',
        action: function (tb, item) {
            config.content = url;
            config.title = SystemUtil.lang.create;
            SystemUtil.openUrl2(config);
            SystemUtil.CurrentTableInc = tb;
        }
    });
    return this;
};

ListTable.prototype.topBatchDeleteBar = function (url, config) {
    this.topBars.push({
        html: '<button class="layui-btn layui-btn-sm layui-btn-danger"><i class="iconfont icon-ic_delete"></i>' + SystemUtil.lang.batch_delete + '</button>',
        action: function (tb, item) {
            let checkStatus = layui.table.checkStatus(tb.config.id)
                , data = checkStatus.data, ids = [];
            if (data.length) {
                layer.confirm(SystemUtil.lang.batch_delete_confirm, {
                    skin: 'layui-layer-admin',
                    title: SystemUtil.lang.tip,
                    btn: [SystemUtil.lang.ok, SystemUtil.lang.cancel],
                    shade: .1
                }, function (i) {
                    layer.close(i);
                    data.forEach(function (item) {
                        ids.push(item.id);
                    });
                    SystemUtil
                        .ajax(url)
                        .setData({ids})
                        .send(3)
                        .then(() => {
                            tb.reload();
                        });
                });
            } else {
                layer.alert(SystemUtil.lang.batch_delete_no_data, {
                    title: SystemUtil.lang.tip,
                    btn: [SystemUtil.lang.ok],
                });
            }
        }
    });
    return this;
};
/**
 * 设置表头按钮
 * @param html
 * @param action
 * @returns {ListTable}
 */
ListTable.prototype.topAction = function (html, action) {
    this.topBars.push({
        html: html,
        action: action
    });
    return this;
};

ListTable.prototype.topImportBar = function (type, importUrl, tplUrl, call, data, options) {
    let _options = options || {};
    this.topAction('<button class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe681;</i>' + (_options.importBtn || "导入") + '</button>', function (tb) {
            const confirmIdx = layui.layer.confirm('确认导入数据？', {
                title: SystemUtil.lang.tip,
                btn: [SystemUtil.lang.ok, SystemUtil.lang.cancel]
            }, function () {
                layui.layer.close(confirmIdx);
                let input = document.createElement("input");
                input.type = "file";
                input.click();
                input.onchange = function () {
                    let file = input.files[0];
                    let run = function (_data) {
                        let form = new FormData();
                        form.append("file", file); //第一个参数是后台读取的请求key值
                        if (_data) {
                            layui.$.each(_data, function (key, value) {
                                form.append(key, value);
                            });
                        }
                        SystemUtil.ajax(importUrl)
                            .setData(form)
                            .set('processData', false)
                            .set('contentType', false)
                            .send(1)
                            .done(function (res) {
                                layer.alert(res.msg, {title: '导入信息'});
                                if (call) {
                                    call(res.data, tb);
                                }
                            });
                    };
                    if (data && typeof data === 'function') {
                        data(run, tb);
                    } else {
                        run();
                    }
                }
            });
        }
    );

    this.topAction('<button class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe60a;</i>导入日志</button>', function (res) {
        layer.open({
            type: 2,
            title: '导入日志',
            content: SystemUtil.BaseURL + "system.importLog/index?type=" + type,
            area: ['80%', '80%'],
            shadeClose: true,
            scrollbar: false
        });
    });
    this.topAction("<button class=\"layui-btn layui-btn-sm\"><i class=\"layui-icon\">&#xe601;</i>下载导入模板</button>", function () {
        SystemUtil.downFile(tplUrl);
    });
};

ListTable.prototype.setSelectIds = function (ids) {
    return SystemUtil.ajax(SystemUtil.BaseURL + "/import/setSelectIds").setData({
        ids: ids,
    }).send(layui.$);
};

ListTable.prototype.actionBar = function (html, action, filter) {
    this.rowBars.push({
        html: html,
        filter: filter,
        action: action
    });
    return this;
};

/**
 *
 * @param call
 * @param filter
 * @returns {ListTable}
 */
ListTable.prototype.editBar = function (call, filter) {
    let that = this;
    this.contextMenu.push({
        icon: 'iconfont icon-ic_edit',
        name: SystemUtil.lang.edit,
        filter,
        action: call
    });
    return that.actionBar('<button type="button" class="layui-btn layui-btn-xs" title="' + SystemUtil.lang.edit + '">' + SystemUtil.lang.detail + '</button>', call, filter);
};

ListTable.prototype.confirmBar = function (html, confirmText, call, filter) {
    return this.actionBar(html, this.confirmAction(confirmText, call), filter);
};
ListTable.prototype.confirmAction = function (confirmText, call) {
    let that = this;
    return function (tb, item) {
        layer.confirm(confirmText, {
            skin: 'layui-layer-admin',
            title: SystemUtil.lang.tip,
            btn: [SystemUtil.lang.ok, SystemUtil.lang.cancel],
            shade: .1
        }, function (i) {
            layer.close(i);
            let loadIndex = layer.load(2);
            call(tb, item).send(3)
                .then(() => {
                    that.tableInc.reload();
                });
        });
    };
};
/**
 *
 * @param call
 * @param filter
 * @returns {ListTable}
 */
ListTable.prototype.showBar = function (call, filter) {
    let that = this;
    this.contextMenu.push({
        icon: 'layui-icon layui-icon-list',
        name: SystemUtil.lang.detail,
        filter,
        action: call
    });
    return that.actionBar('<button type="button" class="layui-btn layui-btn-xs" title="' + SystemUtil.lang.detail + '">' + SystemUtil.lang.detail + '</button>', call, filter);
};


//选项卡
ListTable.prototype.tabBar = function (html, title, url, filter, field) {
    this.rowBars.push({
        html: html,
        filter: filter,
        action: function (tb, data) {
            index.openNewTab({
                name: title,
                url: url + '/id=' + data[field || 'id']
            });
        }
    });
    return this;
};

ListTable.prototype.delBar = function (call, filter) {
    this.contextMenu.push({
        icon: 'iconfont icon-ic_delete text-danger',
        name: SystemUtil.lang.delete,
        filter,
        action: this.confirmAction(SystemUtil.lang.delete_confirm, call)
    });
    return this.confirmBar('<button type="button" class="layui-btn layui-btn-xs layui-btn-danger" >'+SystemUtil.lang.delete+'</button>', SystemUtil.lang.delete_confirm, call, filter);
};

ListTable.prototype.clearCols = function () {
    this.config.cols = [[]];
};

ListTable.prototype.getUrl = function () {
    if (this.url.indexOf('?') > -1) {
        return this.url + '&_t=' + new Date().getTime();
    } else {
        return this.url + '?_t=' + new Date().getTime();
    }
};

ListTable.prototype.column = function (title, field) {
    let column = SystemUtil.table.column(title, field);
    this.config.cols[0].push(column);
    return column;
};

ListTable.prototype.lineNumber = function () {
    let column = SystemUtil.table.columns.lineNumber();
    this.config.cols[0].push(column);
    return column;
};

ListTable.prototype.checkbox = function () {
    this.config.cols[0].push(SystemUtil.table.columns.checkbox());
    return this;
};

ListTable.prototype.radio = function () {
    this.config.cols[0].push(SystemUtil.table.columns.radio());
    return this;
};

ListTable.prototype.buildRowBar = function () {
    //解析 行操作栏
    if (this.rowBars.length) {
        let that = this;
        let rowBarKey = 'rowBar_' + that.baseEventKey;
        let html = '<script type="text/html" id="' + rowBarKey + '">';
        this.rowBars.forEach(function (item) {
            if (item.filter) {
                html += "{{# if(" + item.filter + "){ }}";
            }
            item.key = that.baseEventKey++;
            that.rowEventKeys[item.key] = item;
            html += layui.$(item.html).attr('lay-event', item.key).prop("outerHTML");
            if (item.filter) {
                html += "{{# } }}";
            }
        });
        html += '</script>';
        layui.$(document).find('body').append(layui.$(html));
        this.config.cols[0].push({
            fixed: this.rowBarFixed,
            title: SystemUtil.lang.operation,
            width: this.rowBarWidth,
            align: 'center',
            toolbar: "#" + rowBarKey
        });
    }
};
ListTable.prototype.buildTopBar = function () {
    if (this.topBars.length) {
        let html = '<div><div class="layui-btn-container">';
        let that = this;
        this.topBars.forEach(function (item) {
            item.key = that.baseEventKey++;
            that.topEventKeys[item.key] = item;
            html += layui.$(item.html).attr('lay-event', item.key).prop("outerHTML");
        });
        html += '</div></div>';
        this.config.toolbar = html;
    } else {
        this.config.toolbar = false;
    }
};


/**
 * 渲染输出
 */
ListTable.prototype.render = function (tablePlug, callback) {
    this.baseEventKey = new Date().getTime();
    let that = this;
    tablePlug = tablePlug || "table"
    layui.use(["element", tablePlug, "form", "laydate", "tableX", "contextMenu"], function () {
        let table = layui[tablePlug];
        let form = layui.form;
        let $ = layui.jquery;
        let layFilter = that.config.elem.substring(1);
        $(that.config.elem).attr("lay-filter", layFilter);
        that.buildRowBar();
        that.buildTopBar();
        if (!that.config.data) {
            that.config.url = that.getUrl();
        }
        if (that.contextMenu.length) {
            let oldDone = () => {
            };
            if (that.config.done) {
                oldDone = that.config.done;

            }
            that.config.done = function (res, curr, count) {
                // 绑定鼠标右键
                oldDone(res, curr, count);
                layui.tableX.bindCtxMenu(that.tableId, function (d) {
                    function filterMenu(menus) {
                        let _menus = [];
                        menus.forEach(function (menu) {
                            if (menu.filter) {
                                if (!eval(menu.filter)) {
                                    return;
                                }
                            }
                            if (menu.children) {
                                let children = filterMenu(menu.children);
                                if (children.length) {
                                    menu.subs = children;
                                    _menus.push(menu);
                                }
                            } else {
                                if (!menu.click && menu.action) {
                                    menu.click = function (d) {
                                        menu.action(that.tableInc, d);
                                    }
                                }
                                _menus.push(menu);
                            }
                        });
                        return _menus;
                    }

                    return filterMenu(that.contextMenu);
                });
            };
        }

        //写入请求头
        that.tableInc = table.render(that.config);
        form.on("submit(" + that.searchKey + ")", function (data) {
            that.tableInc.reload({
                where: data.field,
                page: {curr: 1}
            });
            return false;
        });

        if (that.rowBars.length) {
            table.on("tool(" + layFilter + ")", function (obj) {
                let data = obj.data;
                let item = that.rowEventKeys[obj.event];
                item.action(that.tableInc, data, obj);
            });
        }

        if (that.topBars.length) {
            table.on("toolbar(" + layFilter + ")", function (obj) {
                let item = that.topEventKeys[obj.event];
                if (typeof (item.action) == 'function') {
                    item.action(that.tableInc);
                }
            });
        }
        if (callback) {
            callback(that.tableInc);
        }
    });
};


function LayDataTableColumn(title, field) {
    this.title = title;
    this.field = field;
    this.sort = false;
}

LayDataTableColumn.prototype = {
    /**
     * 设置宽度
     * @param width
     * @returns {LayDataTableColumn}
     */
    setWidth: function (width) {
        this.width = width;
        return this;
    },
    /**
     * 设置宽度为日期时间宽度
     * @returns {LayDataTableColumn}
     */
    setWithDateTime: function () {
        this.width = 170;
        return this;
    },
    /**
     * 格式化数据
     * @param unit
     * @param def
     * @param showEmpty
     * @returns {LayDataTableColumn}
     */
    format: function (unit, def, showEmpty) {
        let _this = this;
        this.templet = function (d) {
            if (showEmpty) {
                if (!d[_this.field] && d[_this.field] != 0) {
                    return "";
                }

                if (d[_this.field] == '') {
                    return "";
                }
            }
            return SystemUtil.formatMoney(d[_this.field], def || '0.00', unit || '元');
        };
        return _this;
    },
    setSort: function (sort) {
        this.sort = false;
        return this;
    },
    setTotalRow: function () {
        this.totalRow = true;
        return this;
    },
    showField: function (field) {
        this.templet = function (d) {
            return d[field] || "";
        };
        return this;
    },
    bool: function (yes, no) {
        //负数值
        let _this = this;
        _this.templet = function (d) {
            return d[_this.field] ? (yes || '是') : (no || '否');
        };
        return _this;
    },
    tpl: function (tpl) {
        this.templet = tpl;
        return this;
    },
    setToolbar: function (tpl) {
        this.toolbar = tpl;
        return this;
    },
    turn: function () {
        //负数值
        let _this = this;
        _this.templet = function (d) {
            return -d[_this.field];
        };
        return _this;
    },
    isID: function () {
        let _this = this;
        _this.templet = function (d) {
            return d[_this.field] > 0 ? d[_this.field] : "";
        };
        return _this;
    },
    rate: function (multiple, unit, def, showEmpty) {
        let _this = this;
        _this.templet = function (d) {
            if (showEmpty) {
                if (!d[_this.field] && d[_this.field] != 0) {
                    return "";
                }
            }
            return SystemUtil.formatMoney(d[_this.field] * (multiple || 1), def || '0.00', unit || '%');
        };
        return _this;
    },
    editInput: function () {
        this.edit = 'text';
        return this;
    },

    num: function (unit, isField) {
        let _this = this;
        _this.templet = function (d) {
            if (isField) {
                return SystemUtil.formatMoney(d[_this.field], 0, d[unit] || '件');
            }
            return SystemUtil.formatMoney(d[_this.field], 0, unit || '件');
        };
        return _this;
    },
    dateTime: function (format) {
        let _this = this;
        _this.width = 160;
        _this.templet = function (d) {
            return d[_this.field] > 0 ? SystemUtil.formatTime(d[_this.field], format || "yyyy-MM-dd hh:mm:ss") : "";
        };
        return _this;
    },
    date: function (format) {
        this.dateTime(format || "yyyy-MM-dd");
        this.width = 120;
        return this;
    },
    set: function (k, v) {
        this[k] = v;
        return this;
    }
};
SystemUtil.table = {
    column: function (title, field) {
        return new LayDataTableColumn(title, field);
    },
    columns: {
        opBar: function (width) {
            return {
                fixed: 'right',
                width: width || 95,
                title: SystemUtil.lang.operation,
                align: 'center',
                toolbar: true
            }
        },
        lineNumber: function () {
            return {type: 'numbers', title: SystemUtil.lang.line, fixed: 'left'};
        },
        checkbox: function () {
            return {type: 'checkbox', fixed: 'left'};
        },
        radio: function () {
            return {type: 'radio', fixed: 'left'};
        }
    },
    configTable: function (config, options) {
        layui.use(['table', 'form'], function () {
            let table = layui.table, form = layui.form, $ = layui.jquery;
            let params = $.extend({
                tableId: 'adminTable',
                searchFormFilter: 'search',
                tool: false
            }, options || {});
            //监听搜索
            form.on('submit(' + params.searchFormFilter + ')', function (data) {
                searchWhere = data.field;
                tableIns.reload({
                    where: Object.assign(orderWhere, searchWhere, config.where || {})
                    , page: {
                        curr: 1
                    }
                });
                return false;
            });
            //第一个实例
            let tableIns = table.render($.extend({
                elem: '#' + params.tableId
                , height: 'full-' + (layui.$('#' + params.tableId).get(0).offsetTop + 40)
                , cellMinWidth: 120
            }, config));
            let orderWhere = {}, searchWhere = {};
            table.on('sort(' + params.tableId + ')', function (obj) {
                orderWhere = {
                    order: obj.type,
                    field: obj.field
                };
                tableIns.reload({
                    where: Object.assign(orderWhere, searchWhere, config.where || {})
                });
            });
            table.on('tool(' + params.tableId + ')', function (obj) {
                params.tool(obj, tableIns);
            });
        });
    },
};
layui.use(['layer', 'form', 'admin'], function () {
    let layer = layui.layer, form = layui.form, admin = layui.admin;
    form.on('submit(ajaxForm)', function (data) {
        let set = data.form.dataset, formId = data.form.dataset.id;

        console.log(SystemUtil.tinymceEle, formId);

        if (formId) {
            let elem = SystemUtil.tinymceEle[formId];
            if (elem) {
                elem.forEach(function (item) {
                    let _name = layui.$('#' + item).attr('name');
                    data.field[_name] = tinymce.get(item).getContent();
                });
            }
        }

        let send = function () {
            SystemUtil.ajax(data.form.action)
                .setData(data.field)
                .send(3).done(() => {
                if (set.mode === 'tab') {
                    admin.closeThisTabs();
                } else if (set.mode === 'iframe') {
                    location.reload();
                } else {
                    setTimeout(function () {
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                        if (parent.SystemUtil.CurrentTableInc) {
                            parent.SystemUtil.CurrentTableInc.reload();
                        }
                    }, 3000);
                }
            });
        }
        if (set.confirm) {
            layer.confirm(set.confirm, {
                icon: 8,
                btn: [SystemUtil.lang.ok, SystemUtil.lang.cancel],
                title: SystemUtil.lang.tip
            }, function (i) {
                layer.close(i);
                send();
            });
        } else {
            send();
        }
        return false;
    });
});
